const config = {
    loginPage: 'login',
    homePage: 'home',
    tokenKey: 'authToken',
    redirectKey: 'redirectUrl',
  };

// 检查登录状态
function CheckAuth() {
    const isLoginPage = window.location.pathname.endsWith('login.html');
    const authToken = localStorage.getItem('authToken');

    // 如果未登录且不在登录页
    if (!authToken && !isLoginPage) {        
        sessionStorage.setItem('redirectUrl', window.location.href);
        window.location.href = 'login';
        return;
    }

    // 如果已登录却在登录页
    if (authToken && isLoginPage) {
        window.location.href = 'home';
    }
}

async function AuthReDirection(result){
    if (!result){                    
        const result = await ShowErrorModal('登录超时，跳转到登录界面', {
            title: '登录错误',
            buttons: [
              { 
                text: '取消', 
                type: 'cancel',
                onClick: () => console.log('取消登录')
              },
              { 
                text: '确定', 
                type: 'confirm',
                onClick: () => console.log('执行确认后操作')
              }
            ]
          });
        
        if (result.action === 'confirm') {
            sessionStorage.setItem('redirectUrl', window.location.href);
            window.location.href = 'login';            
        }else{

        }        
        return;
    }else{
        window.location.href = 'home';
    }
}


async function AuthPermissionErr(errorMsg){
    const result = await ShowErrorModal(errorMsg, {
        title: '权限错误',
        buttons: [
          { 
            text: '取消', 
            type: 'cancel',
            onClick: () => console.log('取消登录')
          },
          { 
            text: '确定', 
            type: 'confirm',
            onClick: () => console.log('执行确认后操作')
          }
        ]
      });
    
    if (result.action === 'confirm') {
        
    }else{

    }        
    return;
}


// 登录处理方法
async function handleLogin(e) {
    e.preventDefault();

    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    try {
        const token = await authenticate(username, password);
        setToken(token);
        redirectAfterLogin();
    } catch (error) { 
        ShowErrorModal(error.message, {
            title: '登录错误',
            buttons: [
              { 
                text: '取消', 
                type: 'cancel',
                onClick: () => console.log('取消登录')
              },
              { 
                text: '确定', 
                type: 'confirm',
                onClick: () => console.log('执行确认后操作')
              }
            ]
          });
    }
}

function setToken(token) {
    localStorage.setItem(config.tokenKey, token);
}

function redirectAfterLogin() {
    const redirectUrl = sessionStorage.getItem(config.redirectKey) ||
        config.homePage;
    sessionStorage.removeItem(config.redirectKey);
    window.location.href = redirectUrl;
}

// 登出处理
function LoginOut() {    
    localStorage.removeItem('authToken');
    window.location.href = 'login';
}

// 认证方法（可覆盖实现）
async function authenticate(username, password) {
    try {
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: username,
                password: password
            })
        });

        // 处理 HTTP 错误状态码
        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || '登录请求失败');
        }

        const responseData = await response.json();

        // 根据业务状态码判断
        if (responseData.code === "0") {
            // 假设返回数据结构为 { code: "0", data: { token: "xxx" } }
            return responseData.data.token;
        } else {
            throw new Error(responseData.msg || "登录验证失败");
        }

    } catch (error) {
        // 统一错误处理
        throw new Error(`登录失败: ${error.message}`);
    }
}


function registFunc(event) {
    const modal = document.getElementById('register-modal');

    event.preventDefault(); // 阻止表单默认提交行为

    var username = document.getElementById('register-username').value;
    var password = document.getElementById('register-password').value;
    var name = document.getElementById('register-name').value;
    var company = document.getElementById('register-company').value;
    var department = document.getElementById('register-department').value;

    // 发送 POST 请求（这里使用 fetch API 作为示例）
    fetch('/api/register', { // 替换为你的服务器端点
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: username,
            password: password,
            name:name,
            company:company,
            department:department,
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.code === '0') {
                // 注册成功，关闭弹窗
                modal.style.display = 'none';
                
                ShowNotice({
                    message: '注册成功',
                    type: 'success',
                    duration: 2000
                  });
                
            } else {
                // 注册失败，显示错误信息
                document.getElementById('register-error-message').textContent = data.message;
            }
        })
        .catch(error => {
            // 处理请求错误
            console.error('Error:', error);
            document.getElementById('register-error-message').textContent = '注册时发生错误，请稍后再试。';
        });
}

function BindLogAndOut() {
    const form = document.getElementById('login-form');
    if (form) {
        form.addEventListener('submit', handleLogin);
    }

       // 注册弹窗控制
       const registerBtn = document.getElementById('register-button');
       const modal = document.getElementById('register-modal');
       const closeBtn = document.querySelector('.close');

       registerBtn.addEventListener('click', () => {
           modal.style.display = 'flex';
       });

       closeBtn.addEventListener('click', () => {
           modal.style.display = 'none';
       });

       window.addEventListener('click', (e) => {
           if (e.target === modal) {
               modal.style.display = 'none';
           }
       });
       // 当用户点击注册表单的提交按钮时
       document.getElementById('register-form').addEventListener('submit', registFunc);
}